/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.one2manycall.service.websocket;

import org.kurento.client.KurentoClient;
import org.kurento.client.MediaPipeline;
import org.kurento.client.WebRtcEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  媒体管道，把直播者和观看者连接起来
 *
 *
 */
public class CallMediaPipeline {


    private static final Logger LOGGER = LoggerFactory.getLogger(CallMediaPipeline.class);

    /**
     * 媒体管道
     */

    private MediaPipeline pipeline;
    /**
     * 直播者的 多媒体地址
     */
    private WebRtcEndpoint callerWebRtcEp;
    /**
     * 观看者 多媒体地址
     */
    private WebRtcEndpoint calleeWebRtcEp;

    public CallMediaPipeline(KurentoClient kurento) {
        LOGGER.info("CallMediaPipeline");
        try {
            this.pipeline = kurento.createMediaPipeline();

            this.callerWebRtcEp = new WebRtcEndpoint.Builder(pipeline).build();
            this.calleeWebRtcEp = new WebRtcEndpoint.Builder(pipeline).build();

            this.callerWebRtcEp.connect(this.calleeWebRtcEp);
            this.calleeWebRtcEp.connect(this.callerWebRtcEp);
        } catch (Throwable t) {

            LOGGER.error(t.getLocalizedMessage());

            if (this.pipeline != null) {
                pipeline.release();
            }
        }
    }

    /**
     * 生成sdp 应答 给 直播者
     * @param sdpOffer sdpOffer
     * @return o
     */
    public String generateSdpAnswerForCaller(String sdpOffer) {

        LOGGER.info("generateSdpAnswerForCaller");

        return callerWebRtcEp.processOffer(sdpOffer);
    }

    /**
     * 生成sdp 应答 给 观看者
     * @param sdpOffer sdpOffer
     * @return o
     */
    public String generateSdpAnswerForCallee(String sdpOffer) {
        LOGGER.info("generateSdpAnswerForCallee");
        return calleeWebRtcEp.processOffer(sdpOffer);
    }

    /**
     * 关闭管道
     */
    public void release() {
        if (pipeline != null) {
            pipeline.release();
        }
    }

    /**
     * 获取直播者的地址
     * @return WebRtcEndpoint
     */
    public WebRtcEndpoint getCallerWebRtcEp() {
        return callerWebRtcEp;
    }

    /**
     * 获取观看者的地址
     * @return  WebRtcEndpoint
     */

    public WebRtcEndpoint getCalleeWebRtcEp() {
        return calleeWebRtcEp;
    }

}
